package utils;

import java.sql.*;

public class DBUtil {
//    1. 定义数据库地址
  static String URL = "jdbc:mysql:///AttDB?characterEncoding = UTF8";
  static String USER = "root";
  static String PWD = "root";

//    2. 注册驱动
    static {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
//    3. 获取连接对象
    public static Connection getConn() throws SQLException {
        Connection conn = DriverManager.getConnection(URL, USER, PWD);
        return conn;
    }
//    4.通用的查询
    public static ResultSet query(String sql,Object...keys) {
//       1. 获取连接对象
        ResultSet rs = null;
        try {
            Connection conn = getConn();
//       2. 获取执行sql语句对象
            PreparedStatement pst = conn.prepareStatement(sql);
//       2.5 遍历参数 将参数赋值给？号
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
//       3. 执行sql语句
            rs = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
//    5.通用的update
    public static int update(String sql,Object...keys) {
//       1. 获取连接对象
        int num = 0;
    try {
        Connection conn = getConn();
//       2. 获取执行sql语句对象
        PreparedStatement pst = conn.prepareStatement(sql);
//       2.5 遍历参数 将参数赋值给？号
        for (int i = 0; i < keys.length; i++) {
            pst.setObject((i+1),keys[i]);
        }
//       3. 执行sql语句
        num = pst.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return num;
}

}
